package com.fingard.dsp.bank.directbank.cgb02;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.util.DateHelper;
import com.fingard.xml.XElement;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

import java.util.Calendar;
import java.util.Date;

public class CGB02Transaction extends CGB02Base implements ITransaction {

	//采用流处理方式
	//1、循环调用readRecord()读取一个请求明细，然后写入发银行的XML对象
	//2、发银行
	//3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
	//   然后调用writeRetDetail()，写入返回ATS的明细
	public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception{
		//历史明细查询返回ATS的对象
		RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
		String tmpRespCode = "";
		String tmpRespInfo = "";
		retAts.writeStart();//写返回ATS的统一头部信息
		try {
			Calendar tmpCalendarFrom = Calendar.getInstance();
			tmpCalendarFrom.setTime(p_req7516.getDateFrom());
			
			Calendar tmpCalendarTo = Calendar.getInstance();
			tmpCalendarTo.setTime(p_req7516.getDateTo());
			
			int tmpIntDateFrom = 0;
			int tmpIntDateTo = 0;
			//按自然月循环查询
			while(tmpIntDateFrom<=tmpIntDateTo && tmpRespCode.length() == 0){
				Calendar tmpClndrStepTo = Calendar.getInstance();
				tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
				//判断是否跨月
				if(DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1){
					//跨月则设置为月末
					tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
				}
				else{
					tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
				}
				 
            	CGB02Header bankHeader = new CGB02Header();
				bankHeader.transCode = "0024";
				bankHeader.reqSeqID = getQryTransID();
				XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象
				xmlWriter.autoFormat = false;
				//写入通用的头部节点
				writeCommonHeader(xmlWriter, bankHeader);
				xmlWriter.writeStartElement("Body");
				xmlWriter.writeElementString("account", p_req7516.actNum);
				xmlWriter.writeElementString("beginDate", Format.Date8Format.format(tmpCalendarFrom.getTime()));
				xmlWriter.writeElementString("endDate", Format.Date8Format.format(tmpClndrStepTo.getTime()));
				xmlWriter.writeElementString("queryType", "0");
				xmlWriter.writeEndDocument();
				//测试代码：打印报文
				System.out.println("xmlWriter.toXmlString():\n"+xmlWriter.toXmlString());
			 	String[] tmpStrRet = sendToBank(xmlWriter.toXmlString());
			 	//	String[] tmpStrRet ={"",""};
				XmlTextReader tmpBkReader;
//				tmpStrRet[0]="";
//				tmpStrRet[1]="<?xml version=\"1.0\" encoding=\"gbk\" ?><BEDC><Message><commHead><tranCode>0024</tranCode><cifMaster>1000194103</cifMaster><entSeqNo>1838453005</entSeqNo><tranDate>20160827</tranDate><tranTime>20160827</tranTime><retCode>000</retCode><entUserId>100001</entUserId><password>1</password></commHead><Body><account>9550880200181500150</account><totalNum>1</totalNum><records><record><serialNo>0000001353760001</serialNo><dealDate>20160824</dealDate><loanSign>+</loanSign><dealMoney>33.34</dealMoney><financingSymbol>+</financingSymbol><usableMoney>1000063.01</usableMoney><abstract>结息转入</abstract><dealBranch>199999</dealBranch><upBill/><oppoAccno/><name/><dealTime>213003</dealTime><abstractContent/><dealChannel>BAT</dealChannel><summary/><postScript/><reserve1/><reserve2>199999201608250000001353760001</reserve2><reserve3/><reserve4/></record></records></Body></Message></BEDC>";
 				if(tmpStrRet[0].length() == 0){
					StringBuilder tmpSbMsg = new StringBuilder();
					tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
					if(tmpBkReader != null){
						String retCode = tmpBkReader.getFirstText("/BEDC/Message/commHead/retCode");
                        if (retCode.equals("000")||retCode.equals("200"))//返回200表示查询成功，可以继续后续数据处理
                        {
                        	if (tmpBkReader.getFirstText("/BEDC/Message/Body/totalNum").equals("0"))//返回0表示无记录
                        	{
                                tmpRespCode = "-1";
        					    tmpRespInfo = "银行返回记录为空！";
                                break;
                            }
                            String account = tmpBkReader.getFirstText("/BEDC/Message/Body/account").trim();
                            // #start "提取各返回节点内容"
                            while(tmpBkReader.read("/BEDC/Message/Body/records/record"))
                            {
                            	//tmpRespCode = "0";
         					    tmpRespInfo = "success";
                            	RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
                            	XElement tmpRetNode = tmpBkReader.readedXElement;
                                String dealDate = tmpRetNode.getSingleText("dealDate");
                                String dealTime = tmpRetNode.getSingleText("dealTime");
                                tmpRetDetail.tranDate =DateHelper.getFormat12Date(dealDate);//格式yyyy-MM-dd
                                tmpRetDetail.valueDate = tmpRetDetail.tranDate;//格式yyyy-MM-dd
                                tmpRetDetail.tranTime = tmpRetDetail.tranDate+" "+DateHelper.getFormat8Time(dealTime);//格式"yyyy-MM-dd HH:mm:ss"
                                // #start 提取摘要、备注，摘要和备注中有一个字段含有对账码，通过提取方法获取对账码
                                tmpRetDetail.comment = tmpRetNode.getSingleTextNotNull("summary").trim();
                                tmpRetDetail.usage = tmpRetNode.getSingleTextNotNull("postScript").trim();
                                tmpRetDetail.abstr = pickupAbstr(tmpRetNode.getSingleTextNotNull("reserve4"),tmpRetDetail.usage, tmpRetDetail.comment );
                                tmpRetDetail.actNum = account;
                                tmpRetDetail.recAccNum = tmpRetNode.getSingleTextNotNull("oppoAccno").trim();
                                tmpRetDetail.recAccName = tmpRetNode.getSingleTextNotNull("name").trim();
                                tmpRetDetail.payCode = tmpRetNode.getSingleTextNotNull("upBill").trim();
                                tmpRetDetail.askNumber = tmpRetNode.getSingleTextNotNull("reserve3").trim();
                              //  tmpRetDetail.reqBatchNO = tmpRetNode.getSingleTextNotNull("serialNo").trim();
                                tmpRetDetail.accBal = tmpRetNode.getSingleText("usableMoney");
                                tmpRetDetail.bnkSeqNo = tmpRetNode.getSingleText("serialNo")+account+dealDate;//交易序号（serialNo)+账号（Account）+交易日期
                                // #end
                                // #start "发生额、余额、借贷标志 --借 +-贷"
                                String dealMoney = tmpRetNode.getSingleText("dealMoney");//交易金额
                                String financingSymbol = tmpRetNode.getSingleText("financingSymbol");//正负标志
                                String loanSign = tmpRetNode.getSingleText("loanSign");//借贷标志
                                String tmpAMT=financingSymbol.replaceAll("\\+", "")+dealMoney;
                                if ("-".equals(loanSign))
                                {
                                    if (tmpAMT.indexOf("-") < 0)
                                    {//借正，正常业务
                                    	tmpRetDetail.tranAmt = tmpAMT;
                                    	tmpRetDetail.cdFlag = "1";
                                    }
                                    else
                                    {//借负，银行退票,表示收入
                                    	tmpRetDetail.tranAmt = tmpAMT.replace("-", "");
                                    	tmpRetDetail.cdFlag = "2";//借贷表示置为贷，表示收入
                                    }
                                }
                                else
                                {
                                	if (tmpAMT.indexOf("-") < 0)
                                    {//贷正，正常业务
                                		tmpRetDetail.tranAmt = tmpAMT;
                                		tmpRetDetail.cdFlag = "2";
                                    }
                                    else
                                    {//贷负，目前应该没有这种业务，按照正常的程序逻辑做一下处理
                                    	tmpRetDetail.tranAmt = tmpAMT.replace("-", "");
                                        tmpRetDetail.cdFlag = "1";//借贷表示置为借，表示支出
                                    }
                                }
								tmpRetDetail.originator=tmpRetNode.getSingleTextNotNull("serialNo").trim();//交易流水号
                                // #end
                                retAts.writeRetDetail(tmpRetDetail);
                            }
                        }
                        else
                        {
                            //  "查询失败"
                            tmpRespCode = "-1";
    					    tmpRespInfo = "该帐户没有所要的流水！错误编码："+tmpBkReader.getFirstText("/BEDC/Message/commHead/retCode");
                        }
					}
					else{
						tmpRespCode = "-1";
						tmpRespInfo = tmpSbMsg.toString();
					}
				}
				else{
					tmpRespCode = "-1";
					tmpRespInfo = tmpStrRet[1];
				}
				tmpCalendarFrom = tmpClndrStepTo;
				tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
				tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
				tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
			}
		} catch (Exception e) {
			tmpRespCode = "-1";
			tmpRespInfo = e.getMessage();
			e.printStackTrace();
		}
		if(tmpRespCode.equals("-1")){
			retAts = new RetAtsTrans(p_req7516.reqHeader);
			retAts.writeStart();//写返回ATS的统一头部信息
			retAts.writeRespCode(tmpRespCode);
			retAts.writeRespInfo(tmpRespInfo);
		}
		else if(retAts.getWrittenRdCount() == 0){
			retAts.writeRespCode("0");
			retAts.writeRespInfo("交易为空");
		}
		retAts.writeEnd();
		return retAts;
	}
	
	//当日明细查询调用历史明细查询方法
	public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception{
		Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
		tmpReq7516.actArea = p_req7515.actArea;
		tmpReq7516.actCur = p_req7515.actCur;
		tmpReq7516.actNum = p_req7515.actNum;
		String tmpStrToday = Format.Date8Format.format(new Date());
		tmpReq7516.dateFrom = tmpStrToday;//设置开始时间和结束时间都为当天
		tmpReq7516.dateTo = tmpStrToday;
		return 	d_7516_HisTrans(tmpReq7516);
	}
}
